<?php
namespace wechat;
use think\Controller;

class Openlogin extends Controller {
	
	private $_appId;
    private $_appSecret;
    private $_webRoot;
    private $_openUrlQrc;
    private $_openUrlToken;
    private $_openUrlUserInfo;
    
    public function _initialize(){
        $this->_appId = 'wx06a8c14ed80803a8';//开放平台网站应用
        $this->_appSecret = 'c9bd7e74fbed9dc2eb9257eb4fd99b3a';
        $this->_webRoot = 'http://chongwu.ejucheng.net/pcend.php?s=LoginApi/wxCheck';//返回的域名网址，必须跟网站应用的域名网址相同
        $this->_openUrlQrc = 'https://open.weixin.qq.com/connect/qrconnect';//申请二维码接口
        $this->_openUrlToken = 'https://api.weixin.qq.com/sns/oauth2/access_token';//申请token接口
        $this->_openUrlUserInfo = 'https://api.weixin.qq.com/sns/userinfo';//申请用户信息接口
        header("Content-Type:text/html; charset=utf-8");
    }
    
    /**
    * 提交微信登录请求
    */
    public function wxLogin(){
    	$stats = createnoncestr(16);//该参数可用于防止csrf攻击（跨站请求伪造攻击）
    	session('wx_state',$stats);//把随机字符串写入session，验证时对比
    	
    	$url = $this->_openUrlQrc.'?appid='.$this->_appId.'&redirect_uri='.urlencode($this->_webRoot).'&response_type=code&scope=snsapi_login&state='.$stats;
    	redirect($url);//跳转到扫码
    }

    /**
    * 验证微信扫码后的用户数据
    */
    public function wxCheck(){
        $code = input('get.code');//只能使用1次即销毁
        $state = input('get.state');
        session('wx_state',null);//清除这个session
        $ken = $this -> wxToken($code);//:access_token,expires_in,refresh_token,openid,scope,unionid
        if($ken['errcode'] == 40029){
            $this->error("code参数已经过期");
        }
       
        
        
        $user = $this -> wxUserInfo($ken['access_token'],$ken['openid']);//获取用户信息
        $vip = db(\tname::vip) -> where(array('uid'=>2,'unionid'=>$user['unionid'])) -> find();
        if($vip['id']==null){
            $data = array(
                'uid'	 		=> 2,
                'openid'        => $ken['openid'],
                'unionid' 		=> $user['unionid'],
                'nickname' 		=> $user['nickname'],
                'source' 		=> 1,
                'createtime'	=> time(),
            );
            $res = db(\tname::vip) -> add($data);

            $vipww = db(\tname::vip) -> where(array('id'=>$res)) -> find();
            $pcuserinfo = array(
                'sign' 		  	=> 2,  //登录区分（1手机后登录 2微信扫码登陆）
                'nickname' 		=> $vipww['nickname'],
                'openid'       	=> $vipww['openid'],
                'unionid'       => $vipww['unionid']
            );
            session('pcuserinfo',$pcuserinfo);
		}else{
            $pcuserinfo = array(
                'sign' 		  	=> 2,  //登录区分（1手机后登录 2微信扫码登陆）
                'nickname' 		=> $vip['nickname'],
                'openid'       	=> $vip['openid'],
                'unionid'       => $vip['unionid']
            );
            session('pcuserinfo',$pcuserinfo);
        }
        $this->redirect('Pchome/index');
    }


    //获取token信息
    public function wxToken($code){
        $url = $this->_openUrlToken.'?appid='.$this->_appId.'&secret='.$this->_appSecret.'&code='.$code.'&grant_type=authorization_code';
        $sContent = https_request($url);//获取token数据
        return $sContent;
    }
    
    //延长token时间,默认token两个小时
    public function wxrefresh($refresh){

        $url = 'https://api.weixin.qq.com/sns/oauth2/refresh_token?appid='.$this->_appId.'&grant_type=refresh_token&refresh_token='.$refresh;
        return https_request($url);
    }

    //检验token授权是否有效
    public function wxchecktoken($token,$openid){
        $url = 'https://api.weixin.qq.com/sns/auth?access_token='.$token.'&openid='.$openid;
        return https_request($url);
    }
    //获取微信用户个人信息，但公众号和开放平台opendid 会不一样，unionid是用户唯一标识
    public function wxUserInfo($token,$openid){
        $url = $this->_openUrlUserInfo.'?access_token='.$token.'&lang=zh-CN&openid='.$openid;
        return https_request($url);
    }
}